package org.jsola.hr.service.impl;

import org.jsola.common.DateKit8;
import org.jsola.common.PageKit;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.DateUtils;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ISaleRebatesRecordDAO;
import org.jsola.hr.dto.CalculationRebatesDTO;
import org.jsola.hr.dto.SaleRebatesRecordAddDTO;
import org.jsola.hr.dto.SaleRebatesRecordUpdateDTO;
import org.jsola.hr.entity.*;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.query.SaleRebatesRecordQuery;
import org.jsola.hr.service.*;
import org.jsola.hr.vo.*;
import org.jsola.permission.entity.GroupDO;
import org.jsola.permission.vo.GroupListVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 提成记录
 *
 * @author zhr
 */
@Service("hrSaleRebatesRecordServiceImpl")
public class SaleRebatesRecordServiceImpl implements ISaleRebatesRecordService {

    @Autowired
    private ISaleRebatesRecordDAO saleRebatesRecordDAO;

    @Autowired
    private ICompanySaleUserService companySaleUserService;

    @Autowired
    private ICompanySaleServerService companySaleServerService;

    @Autowired
    private ISaleServerCostRecordService saleServerCostRecordService;

    @Autowired
    private ICompanySaleRebatesRulesService companySaleRebatesRulesService;

    @Autowired
    private ISaleRebatesRulesService saleRebatesRulesService;

    @Autowired
    private ISaleUserService saleUserService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IPermissionProviderService permissionProviderService;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SaleRebatesRecordVO save(SaleRebatesRecordAddDTO saleRebatesRecordAddDTO, TokenUser tokenUser) {
        // 转DO
        SaleRebatesRecordDO saleRebatesRecordDO = saleRebatesRecordAddDTO.to(SaleRebatesRecordDO.class);
        // 保存
        saleRebatesRecordDO = save(saleRebatesRecordDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return saleRebatesRecordDO.to(SaleRebatesRecordVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SaleRebatesRecordUpdateDTO saleRebatesRecordUpdateDTO, TokenUser tokenUser) {
        //转DO
        SaleRebatesRecordDO saleRebatesRecordDO = saleRebatesRecordUpdateDTO.to(SaleRebatesRecordDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(saleRebatesRecordDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... saleRebatesRecordIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) saleRebatesRecordIds);
    }


    @Override
    public SaleRebatesRecordVO selectById(String saleRebatesRecordId, String siteId) {
        SaleRebatesRecordDO saleRebatesRecordDO = selectDOById(saleRebatesRecordId, siteId);
        if (saleRebatesRecordDO == null) {
            return null;
        }
        return saleRebatesRecordDO.to(SaleRebatesRecordVO.class);
    }

    @Override
    public List<SaleRebatesRecordListVO> select(SaleRebatesRecordQuery saleRebatesRecordQuery, String siteId) {
        List<SaleRebatesRecordDO> saleRebatesRecordDOList = selectDO(saleRebatesRecordQuery, siteId);
        if (CollectionUtils.isEmpty(saleRebatesRecordDOList)) {
            return saleRebatesRecordDOList == null ? null : new ArrayList<>();
        }
        return saleRebatesRecordDOList.stream()
                .map(saleRebatesRecordDO -> saleRebatesRecordDO.to(SaleRebatesRecordListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(SaleRebatesRecordQuery saleRebatesRecordQuery, String siteId) {
        Example example = buildExample(saleRebatesRecordQuery, siteId);
        return saleRebatesRecordDAO.selectCountByExample(example);
    }

    @Override
    public Page<SaleRebatesRecordListVO> selectPage(SaleRebatesRecordQuery query, TokenUser tokenUser) {
        List<String> companyIdList = companyService.tileCompanyIdByUser(tokenUser);
        if (CollectionUtils.isEmpty(companyIdList)) {
            return new Page<>(query.getPageSize(), query.getPageNo());
        }
        query.setCompanyIdList(companyIdList);
        Example example = buildExample(query, tokenUser.getSiteId());
        example.orderBy("gmtCreate").desc();
        Page<SaleRebatesRecordDO> page = saleRebatesRecordDAO.selectPageByExample(example,
                query.getPageNo(),
                query.getPageSize());

        return page.to(SaleRebatesRecordListVO.class);
    }

    @Override
    public SaleRebatesRecordDO selectDOById(String saleRebatesRecordId, String siteId) {
        return listById(saleRebatesRecordId, siteId);
    }

    @Override
    public List<SaleRebatesRecordDO> selectDO(SaleRebatesRecordQuery saleRebatesRecordQuery, String siteId) {
        Example example = buildExample(saleRebatesRecordQuery, siteId);
        return saleRebatesRecordDAO.selectByExample(example);
    }

    @Override
    public CalculationRebatesVO calculationRebates(CalculationRebatesDTO calculationRebatesDTO, TokenUser tokenUser) {
        ParamException.notNull(calculationRebatesDTO.getBeginTime(), "请选择开始时间");
        ParamException.notNull(calculationRebatesDTO.getEndTime(), "请选择结束时间");
        CalculationRebatesVO result = new CalculationRebatesVO();
        List<CalculationRebatesErrorInfoVO> errorInfoList = new ArrayList<>();
        List<String> companyIdList = calculationRebatesDTO.getCompanyIdList();
        ParamException.notEmpty(companyIdList, "请选择用工单位");
        Date beginTime = DateKit8.parseDate(calculationRebatesDTO.getBeginTime() + "-01");
        Date endTime = DateKit8.parseDate(calculationRebatesDTO.getEndTime() + "-01");
        // 获取开始和结束之间的月份(包含开始结束时间)
        List<Date> monthDifferences = DateUtils.getMonthDifferences(beginTime, endTime);
        List<CompanyDO> companyList = companyService.selectByIds(companyIdList, tokenUser.getSiteId());
        Map<String, CompanyDO> companyMap = companyList.stream()
                .collect(Collectors.toMap(CompanyDO::getId, v -> v));
        for (String companyId : companyIdList) {
            CompanyDO company = companyMap.get(companyId);
            // 查询这个用工单位的服务列表
            List<CompanySaleServerDO> companySaleServerList = companySaleServerService
                    .selectCompanyServerList(companyId, tokenUser.getSiteId());
            if (CollectionUtils.isEmpty(companySaleServerList)) {
                CalculationRebatesErrorInfoVO errorInfo = new CalculationRebatesErrorInfoVO();
                errorInfo.setCompanyName(company.getName());
                errorInfo.setErrorInfo("用工单位没有绑定合同信息");
                errorInfoList.add(errorInfo);
                continue;
            }
            // 找出这个用工单位绑定的提成规则
            CompanySaleRebatesRulesDO companySaleRebatesRules = companySaleRebatesRulesService
                    .selectRulesByCompanyId(companyId, tokenUser.getSiteId());
            if (ObjectUtils.isEmpty(companySaleRebatesRules)) {
                CalculationRebatesErrorInfoVO errorInfo = new CalculationRebatesErrorInfoVO();
                errorInfo.setCompanyName(company.getName());
                errorInfo.setErrorInfo("用工单位没有绑定提成规则");
                errorInfoList.add(errorInfo);
                continue;
            }
            // 拿到提成规则
            SaleRebatesRulesDO saleRebatesRules = saleRebatesRulesService
                    .selectDOById(companySaleRebatesRules.getRebatesRulesId(), tokenUser.getSiteId());
            // 把这个用工单位下所有的客户服务费金额导入记录找出来
            List<SaleServerCostRecordDO> serverCostRecordList = saleServerCostRecordService
                    .selectCompanyRecord(companyId, tokenUser);
            Map<String, SaleServerCostRecordDO> serverCostRecordMap = serverCostRecordList.stream()
                    .collect(Collectors.toMap(SaleServerCostRecordDO::getCostMonth, v -> v));
            ParamException.notNull(company, "存在已被删除的用工单位");
            // 查询用工单位下的销售
            List<CompanySaleUserDO> saleUserList = companySaleUserService
                    .selectSaleUserByCompanyId(companyId, tokenUser.getSiteId());
            if (CollectionUtils.isEmpty(saleUserList)) {
                CalculationRebatesErrorInfoVO errorInfo = new CalculationRebatesErrorInfoVO();
                errorInfo.setCompanyName(company.getName());
                errorInfo.setErrorInfo("用工单位没有绑定销售");
                errorInfoList.add(errorInfo);
                continue;
            }
            List<SaleRebatesRecordDO> saveList = new ArrayList<>();
            for (Date monthDifference : monthDifferences) {
                // 把时间类型变成 2022-08 这种字符串
                String calculationMonth = DateUtils.getYearMonthByDate(monthDifference);
                // 把原来的对应的  用工单位下的对应月份的 提成记录删掉 然后再创建新的
                this.deleteSaleRebatesRecord(companyId, calculationMonth);
                Boolean isFirst = null;
                // 根据用工单位详情里的服务列表  判断当前是新增还是续约
                for (CompanySaleServerDO companySaleServer : companySaleServerList) {
                    Date serverBeginTime = companySaleServer.getServerBeginTime();
                    Date serverEndTime = companySaleServer.getServerEndTime();
                    String yearMonthStr = DateUtils.getYearMonthStr(monthDifference);
                    Boolean isWithinRange = DateUtils
                            .compareWithinRange(serverBeginTime, serverEndTime, yearMonthStr);
                    if (isWithinRange) {
                        isFirst = companySaleServer.getIsFirst();
                        break;
                    }
                }
                if (ObjectUtils.isEmpty(isFirst)) {
                    CalculationRebatesErrorInfoVO errorInfo = new CalculationRebatesErrorInfoVO();
                    errorInfo.setCompanyName(company.getName());
                    errorInfo.setMonth(calculationMonth);
                    errorInfo.setErrorInfo(calculationMonth + "用工单位不存在对应的服务合作时间段，无法计算");
                    errorInfoList.add(errorInfo);
                    continue;
                }
                for (CompanySaleUserDO companySaleUser : saleUserList) {
                    // 分成比例
                    BigDecimal dividedProportion = companySaleUser.getDividedProportion();
                    SaleServerCostRecordDO serverCostRecord = serverCostRecordMap.get(calculationMonth);
                    if (ObjectUtils.isEmpty(serverCostRecord)) {
                        CalculationRebatesErrorInfoVO errorInfo = new CalculationRebatesErrorInfoVO();
                        errorInfo.setCompanyName(company.getName());
                        errorInfo.setMonth(calculationMonth);
                        errorInfo.setErrorInfo(calculationMonth + "没有客户服务费导入记录");
                        errorInfoList.add(errorInfo);
                        continue;
                    }
                    BigDecimal serverCost = serverCostRecord.getServerCost();
                    // 组织提成记录对象
                    SaleRebatesRecordDO saleRebatesRecord = new SaleRebatesRecordDO();
                    saleRebatesRecord.setSaleName(companySaleUser.getSaleName());
                    saleRebatesRecord.setCompanyId(companyId);
                    saleRebatesRecord.setCompanyName(company.getName());
                    saleRebatesRecord.setCalculationMonth(calculationMonth);
                    saleRebatesRecord.setSaleUserId(companySaleUser.getSaleUserId());
                    saleRebatesRecord.setServerCost(serverCost);
                    saleRebatesRecord.setIsNew(isFirst);
                    saleRebatesRecord.setRebatesRulesId(saleRebatesRules.getId());
                    saleRebatesRecord.setRulesName(saleRebatesRules.getRulesName());
                    BigDecimal proportion = isFirst ?
                            saleRebatesRules.getNewProportion() : saleRebatesRules.getContinueProportion();
                    saleRebatesRecord.setProportion(proportion);
                    saleRebatesRecord.setDividedProportion(dividedProportion);
                    saleRebatesRecord.setRebatesAmount(serverCost
                            .multiply(proportion.multiply(new BigDecimal("0.01")))
                            .multiply(dividedProportion.multiply(new BigDecimal("0.01"))));
                    saleRebatesRecord.preInsert(tokenUser.getUserId());
                    saleRebatesRecord.setSiteId(tokenUser.getSiteId());
                    saveList.add(saleRebatesRecord);
                }
            }
            if (!CollectionUtils.isEmpty(saveList)) {
                bachSave(saveList);
            }
        }
        result.setErrorCount(errorInfoList.size());
        result.setErrorInfoList(errorInfoList);
        return result;
    }

    /**
     * 批量删除提成记录
     */
    private void deleteSaleRebatesRecord(String companyId, String calculationMonth) {
        saleRebatesRecordDAO.deleteSaleRebatesRecord(companyId, calculationMonth);
    }

    @Override
    public void bachSave(List<SaleRebatesRecordDO> saveList) {
        saleRebatesRecordDAO.insertListAndSetId(saveList);
    }

    @Override
    public List<SaleRebatesRecordDO> selectRecordByUserId(SaleRebatesRecordQuery query, TokenUser tokenUser) {
        Example example = buildExample(query, tokenUser.getSiteId());
        example.and().andEqualTo("saleUserId", tokenUser.getUserId());
        return saleRebatesRecordDAO.selectByExample(example);
    }

    @Override
    public MyCommissionVO myCommission(SaleRebatesRecordQuery query, TokenUser tokenUser) {
        MyCommissionVO myCommission = new MyCommissionVO();
        List<MyCommissionRecordVO> recordList = new ArrayList<>();
        List<SaleRebatesRecordDO> saleRebatesRecordList = this.selectRecordByUserId(query, tokenUser);
        if (CollectionUtils.isEmpty(saleRebatesRecordList)) {
            return new MyCommissionVO();
        }
        BigDecimal myCommissionAmount = new BigDecimal("0");
        for (SaleRebatesRecordDO record : saleRebatesRecordList) {
            myCommissionAmount = myCommissionAmount.add(record.getRebatesAmount());
        }
        Map<String, List<SaleRebatesRecordDO>> groupRecord = saleRebatesRecordList.stream()
                .collect(Collectors.groupingBy(SaleRebatesRecordDO::getCalculationMonth));
        for (String month : groupRecord.keySet()) {
            MyCommissionRecordVO myCommissionRecord = new MyCommissionRecordVO();
            myCommissionRecord.setCostMonth(month);
            myCommissionRecord.setDetailList(groupRecord.get(month));
            recordList.add(myCommissionRecord);
        }
        recordList = recordList.stream()
                .sorted(Comparator.comparing(MyCommissionRecordVO::getCostMonth).reversed())
                .collect(Collectors.toList());
        myCommission.setMyCommission(myCommissionAmount);
        myCommission.setRecordList(recordList);
        return myCommission;
    }

    @Override
    public List<CompanyDO> selectCompanyByUser(TokenUser tokenUser) {
        List<SaleRebatesRecordDO> saleRebatesRecordList = this
                .selectRecordByUserId(new SaleRebatesRecordQuery(), tokenUser);
        if (CollectionUtils.isEmpty(saleRebatesRecordList)) {
            return new ArrayList<>();
        }
        List<String> companyIdList = saleRebatesRecordList.stream()
                .map(SaleRebatesRecordDO::getCompanyId).collect(Collectors.toList());
        return companyService.selectByIds(companyIdList, tokenUser.getSiteId());
    }

    @Override
    public Page<SaleRebatesRecordListVO> rebateOverviewList(SaleRebatesRecordQuery query, TokenUser tokenUser) {
        ParamException.notNull(query.getGroupId(), "请选择筛选分组");
        this.buildSaleRebatesRecordQuery(query, tokenUser);
        List<SaleRebatesRecordListVO> result = new ArrayList<>();
        if (!StringUtils.isEmpty(query.getRegion())) {
            String areaName = adminProviderService.selectAreaById(query.getRegion());
            query.setRegion(areaName);
        }
        List<Date> monthDifferences = DateUtils
                .getMonthDifferences(DateKit8.parseDate(query.getBeginTime() + "-01"),
                        DateKit8.parseDate(query.getEndTime() + "-01"));
        if (monthDifferences.size() > 12) {
            throw new ParamException("时间选取区间最大为12个月份");
        }
        List<SaleRebatesRecordListVO> saleRebatesRecordList = saleRebatesRecordDAO
                .rebateOverviewList(query, tokenUser.getSiteId());
        if (CollectionUtils.isEmpty(saleRebatesRecordList)) {
            return new Page<>(query.getPageSize(), query.getPageNo());
        }
        List<String> saleUserIdList = saleRebatesRecordList.stream()
                .map(SaleRebatesRecordListVO::getSaleUserId).distinct().collect(Collectors.toList());
        // 查询销售列表以userId分组
        List<SaleUserDO> saleUserList = saleUserService.selectBySaleUserIdList(saleUserIdList, tokenUser);
        Map<String, SaleUserDO> saleUserMap = saleUserList.stream()
                .collect(Collectors.toMap(SaleUserDO::getSaleUserId, v -> v));
        // 拿到他们的所属分组
        List<String> groupIdList = saleUserList.stream()
                .map(SaleUserDO::getSaleGroupId).distinct().collect(Collectors.toList());
        List<GroupListVO> groupsList = permissionProviderService.findGroupsByIds(groupIdList, tokenUser.getSiteId());
        Map<String, GroupListVO> groupMap = groupsList.stream().collect(Collectors.toMap(GroupListVO::getId, v -> v));
        // 以销售人员分组
        Map<String, List<SaleRebatesRecordListVO>> groupRecord = saleRebatesRecordList.stream()
                .collect(Collectors.groupingBy(SaleRebatesRecordListVO::getSaleUserId));
        for (String saleUserId : groupRecord.keySet()) {
            List<SaleRebatesRecordListVO> saleUserRecordList = groupRecord.get(saleUserId);
            if (!CollectionUtils.isEmpty(saleUserRecordList)) {
                BigDecimal amount = new BigDecimal("0");
                for (SaleRebatesRecordListVO saleRebatesRecord : saleUserRecordList) {
                    amount = amount.add(saleRebatesRecord.getRebatesAmount());
                }
                SaleUserDO saleUser = saleUserMap.get(saleUserId);
                List<CompanyVO> companyList = companySaleUserService.selectCompanyBySaleUserId(saleUserId, tokenUser);
                String companyNames = companyList.stream()
                        .map(CompanyVO::getName)
                        .distinct().collect(Collectors.joining("、"));
                SaleRebatesRecordListVO resultRecord = new SaleRebatesRecordListVO();
                resultRecord.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
                resultRecord.setSaleName(saleUser.getSaleName());
                resultRecord.setCompanyName(companyNames);
                resultRecord.setSalePhone(saleUser.getSalePhone());
                resultRecord.setSaleIdCard(saleUser.getSaleIdCard());
                resultRecord.setRegion(saleUser.getRegion());
                resultRecord.setRebatesAmount(amount);
                resultRecord.setSaleUserId(saleUserId);
                GroupListVO group = groupMap.get(saleUser.getSaleGroupId());
                resultRecord.setSaleGroup(group.getName());
                result.add(resultRecord);
            }
        }
        return PageKit.startPage(result, query.getPageNo(), query.getPageSize());
    }

    @Override
    public RebateOverviewGroupVO rebateOverviewGroup(SaleRebatesRecordQuery query, TokenUser tokenUser) {
        ParamException.notNull(query.getGroupId(), "请选择筛选分组");
        // 只显示当前选择的分组的下一级分组和直属销售的金额
        List<GroupDO> subordinateGroup = permissionProviderService
                .selectGroupByParentId(query.getGroupId(), tokenUser);
        this.buildSaleRebatesRecordQuery(query, tokenUser);
        List<SaleRebatesRecordListVO> saleRebatesRecordList = saleRebatesRecordDAO
                .rebateOverviewList(query, tokenUser.getSiteId());
        // 返回值定义
        RebateOverviewGroupVO result = new RebateOverviewGroupVO();
        List<Date> monthDifferences = DateUtils
                .getMonthDifferences(DateKit8.parseDate(query.getBeginTime() + "-01"),
                        DateKit8.parseDate(query.getEndTime() + "-01"));
        if (CollectionUtils.isEmpty(saleRebatesRecordList) || monthDifferences.size() > 12) {
            result.setAllAmount(new BigDecimal("0"));
            result.setDirectlyUnder(new BigDecimal("0"));
            return result;
        }
        Map<String, List<SaleRebatesRecordListVO>> groupRecord = saleRebatesRecordList.stream()
                .collect(Collectors.groupingBy(SaleRebatesRecordListVO::getSaleGroupId));
        BigDecimal allAmount = new BigDecimal("0");
        Map<String, BigDecimal> subordinate = new LinkedHashMap<>(16);
        // 当前选中分组销售提成金额
        BigDecimal directlyUnder = new BigDecimal("0");
        for (SaleRebatesRecordListVO record : saleRebatesRecordList) {
            if (record.getSaleGroupId().equals(query.getGroupId())) {
                directlyUnder = directlyUnder.add(record.getRebatesAmount());
            }
        }
        subordinate.put("分组直属人员", directlyUnder);
        // 循环所有直属分组
        for (GroupDO childGroup : subordinateGroup) {
            // 拿到直属分组的所有子组Id
            List<String> childIdList = permissionProviderService
                    .selectGroupByIdByParent(Collections.singletonList(childGroup.getId()), tokenUser.getSiteId());
            BigDecimal subordinateAmount = new BigDecimal("0");
            for (String groupId : groupRecord.keySet()) {
                if (childIdList.contains(groupId)) {
                    List<SaleRebatesRecordListVO> recordList = groupRecord.get(groupId);
                    for (SaleRebatesRecordListVO record : recordList) {
                        subordinateAmount = subordinateAmount.add(record.getRebatesAmount());
                        allAmount = allAmount.add(record.getRebatesAmount());
                    }
                }
            }
            subordinate.put(childGroup.getName(), subordinateAmount);
        }
        allAmount = allAmount.add(directlyUnder);
        result.setDirectlyUnder(directlyUnder);
        result.setSubordinate(subordinate);
        result.setAllAmount(allAmount);
        return result;
    }

    @Override
    public RebateOverviewMonthVO rebateOverviewMonth(SaleRebatesRecordQuery query, TokenUser tokenUser) {
        ParamException.notNull(query.getGroupId(), "请选择筛选分组");
        ParamException.notNull(query.getBeginTime(), "请选择开始月份");
        ParamException.notNull(query.getEndTime(), "请选择截至月份");
        Date beginTime = DateKit8.parseDate(query.getBeginTime() + "-01");
        Date endTime = DateKit8.parseDate(query.getEndTime() + "-01");
        this.buildSaleRebatesRecordQuery(query, tokenUser);
        RebateOverviewMonthVO result = new RebateOverviewMonthVO();
        List<SaleRebatesRecordListVO> saleRebatesRecordList = saleRebatesRecordDAO
                .rebateOverviewList(query, tokenUser.getSiteId());
        List<Date> monthDifferences = DateUtils.getMonthDifferences(beginTime, endTime);
        if (CollectionUtils.isEmpty(saleRebatesRecordList) || monthDifferences.size() > 12) {
            return result;
        }
        // 以月份分组
        Map<String, List<SaleRebatesRecordListVO>> groupRecord = saleRebatesRecordList.stream()
                .collect(Collectors.groupingBy(SaleRebatesRecordListVO::getCalculationMonth));
        Map<String, BigDecimal> monthAmount = new LinkedHashMap<>(16);
        for (Date monthDifference : monthDifferences) {
            String monthDifferenceStr = DateUtils.getYearMonthByDate(monthDifference);
            List<SaleRebatesRecordListVO> recordList = groupRecord.get(monthDifferenceStr);
            BigDecimal bigDecimal = new BigDecimal("0");
            if (!CollectionUtils.isEmpty(recordList)) {
                for (SaleRebatesRecordListVO record : recordList) {
                    bigDecimal = bigDecimal.add(record.getRebatesAmount());
                }
            }
            monthAmount.put(monthDifferenceStr, bigDecimal);
        }
        result.setMonthAmount(monthAmount);
        return result;
    }

    private void buildSaleRebatesRecordQuery(SaleRebatesRecordQuery query, TokenUser tokenUser) {
        if (!ObjectUtils.isEmpty(query.getEndTime())) {
            query.setEndTimeStr(query.getEndTime());
        }
        if (!ObjectUtils.isEmpty(query.getBeginTime())) {
            query.setBeginTimeStr(query.getBeginTime());
        }
        List<String> queryGroupId = permissionProviderService
                .selectGroupByIdByParent(Collections.singletonList(query.getGroupId()), tokenUser.getSiteId());
        query.setGroupIdList(queryGroupId);
    }

    /**
     * 根据查询参数，构建example
     *
     * @param saleRebatesRecordQuery 查询参数
     * @param siteId                 所属站点id
     * @return example
     */
    private Example buildExample(SaleRebatesRecordQuery saleRebatesRecordQuery, String siteId) {
        Example example = new Example(SaleRebatesRecordDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (!StringUtils.isEmpty(saleRebatesRecordQuery.getCompanyOrSaleName())) {
            example.and()
                    .orLike("companyName", "%" + saleRebatesRecordQuery.getCompanyOrSaleName() + "%")
                    .orLike("saleName", "%" + saleRebatesRecordQuery.getCompanyOrSaleName() + "%");
        }
        if (!StringUtils.isEmpty(saleRebatesRecordQuery.getRulesName())) {
            example.and()
                    .andLike("rulesName", "%" + saleRebatesRecordQuery.getRulesName() + "%");
        }
        if (!ObjectUtils.isEmpty(saleRebatesRecordQuery.getEndTime())) {
            example.and().andLessThanOrEqualTo("calculationMonth", saleRebatesRecordQuery.getEndTime());
        }
        if (!ObjectUtils.isEmpty(saleRebatesRecordQuery.getBeginTime())) {
            example.and().andGreaterThanOrEqualTo("calculationMonth", saleRebatesRecordQuery.getBeginTime());
        }
        if (!StringUtils.isEmpty(saleRebatesRecordQuery.getCompanyId())) {
            example.and().andEqualTo("companyId", saleRebatesRecordQuery.getCompanyId());
        }
        if (!CollectionUtils.isEmpty(saleRebatesRecordQuery.getCompanyIdList())) {
            example.and().andIn("companyId", saleRebatesRecordQuery.getCompanyIdList());
        }
        return example;
    }
}




